<template>
 <div class="d-flex flex-column">
 <!--上部分导航条部分-->
 <nav class="navbar col-lg-12 col-12 p-0 d-flex flex-row justify-content-start">
      <div class="navbar-brand align-items-center d-flex flex-row justify-content-center col-2" style="height: 60px;">
        <span>师生交流预约系统</span>
        <button></button>
      </div>
      <div class="d-flex col justify-end align-items-center" id="navbarSupportedContent">
        <div class="d-flex w-75 justify-content-center">
          <input class="form-control mr-2 w-75" type="search" placeholder="Search" aria-label="Search">
          <button class="btn btn-outline-success" type="submit">Search</button>
        </div>
        <div class="d-flex align-items-center">
          <el-badge :value="messageLength" class="item" type="primary">
          <img class="d-flex mr-3" @click="drawer = true"  src="D:\vue _workspace\chat_platform\src\imgs\message-square.svg" alt="">
          </el-badge>
          <el-drawer v-model="drawer" title="I am the title" :with-header="false">
            <h6 class="text-center">消息</h6>
            <ul>
                  <li v-for="(item,index) in senderList" :key="index">
                  
                  <div class="row">
                    <div class="col-sm-12 py-2 border">
                        <div class="row mt-1 d-flex">
                          <div class="col-2 col-sm-2">
                            <el-avatar class="text-black bg-blue-300">{{ item }}</el-avatar>
                          </div>
                          <div class="d-flex align-items-center col-8">
                          <div @click="selectDialog(item,messageNumber[item],index)" class="m-0 col-7 text-truncate">有{{ messageNumber[item] }}条未读消息</div>

                          <el-dialog v-model="dialogMessage[item]" :title="item" width="500" :show-close="false">
                              <div style="height: 500px;">
                                <div class="h-3/4 overflow-auto border-y border-black" :id="'chatWindow'+index" @scroll="getChange()"> 
                                  <div class="container">
                                      <ul class="px-0">
                                          <li v-for="(item1,index1) in messageList[item]" :key="index1">
                                          <div class="row">
                                            <div class="col-sm-12 my-2">
                                                <p class="text-center mb-2">{{ item1.send_time }}</p>
                                                <div :class="isSelf(item1.sender_name)">
                                                  <div class="col-2 col-sm-2 d-flex justify-content-center">
                                                    <el-avatar class="text-black bg-blue-300">{{ item1.sender_name }}</el-avatar>
                                                  </div>
                                                  <div class="d-flex align-items-center col-auto border rounded max-w-80">
                                                  <p class="m-0 mx-2">{{ item1.content }}</p>
                                                  </div>
                                                  </div>
                                            </div>
                                        </div>
                                          </li>
                                      </ul>
                                    </div>
                                </div>
                                <div class="flex h-1/4 justify-content-end rounded-bottom">
                                  <textarea  @keyup.enter="sendMessage(receiverID[item],item,index)" class="flex form-control p-0" id="exampleFormControlTextarea1" v-model="inputMessage" rows="2"></textarea>
                                  <button type="button" @click="sendMessage(receiverID[item],item,index)"  class="btn btn-outline-primary align-self-end m-3" style="position: absolute;">发送</button>
                                  <button type="button" @click="closeChatWindow(item)" class="btn btn-outline-primary align-self-end my-3 mx-19" style="position: absolute;">退出</button>
                                </div>
                              </div>
                           </el-dialog>


                          </div>
                          <div class="d-flex align-items-center col-1"></div>
                          </div>
                    </div>
                </div>
                  </li>
              </ul>


          </el-drawer>
          <img class="d-flex m-3" @click="open" src="D:\vue _workspace\chat_platform\src\imgs\bell.svg" alt="">
          <span @click="goToInfo()" class="d-flex font-weight-normal mr-5">{{ user_name }}</span>
          <RouterLink :to="{path:'/'}" class="d-flex btn btn-outline-primary mr-5"  type="button">退出登录</RouterLink>
        </div>
      </div>
  </nav>
  <!--左侧导航条-->
<div class="row col-lg-12 col-12" style="font-size: 15px;">
  <ul class="nav flex-column col-2" style="padding-left: 30px;">
  <li class="nav-item d-flex flex-row">
    <img class="flex" src="D:\vue _workspace\chat_platform\src\imgs\circle.svg" width="18px" height="38.5px" alt="">
     <RouterLink :to="{path:'/index/introduce',query:{user_id:user_id}}" class="flex nav-link active text-dark" href="#">首页</RouterLink>
  </li>
  <li class="nav-item d-flex flex-row">
    <img class="flex" src="D:\vue _workspace\chat_platform\src\imgs\home.svg"  width="18px" height="38.5px" alt="">
     <RouterLink :to="{path:'/index/chatroom',query:{user_id:user_id}}" class="flex nav-link active text-dark" href="#">聊天室</RouterLink>
  </li>
  <li class="nav-item d-flex flex-row">
    <img class="flex" src="D:\vue _workspace\chat_platform\src\imgs\clock.svg" width="18px" height="38.5px" alt="">
     <button @click="goReserve()" class="flex nav-link active text-dark" href="#">预约</button>
  </li>
 
  <li class="nav-item">
            <div class="d-flex flex-row">
              <img class="flex" src="D:\vue _workspace\chat_platform\src\imgs\menu.svg"  width="18px" height="38.5px" alt="">
            <RouterLink :to="{path:'/index/projectAll',query:{user_id:user_id,user_name:user_name}}" class="nav-link " data-toggle="collapse" aria-expanded="true" aria-controls="auth">
              <span class="menu-title text-dark">科创项目</span>
              <i class="menu-arrow"></i>
            </RouterLink>
            <img @click="changImg" class="flex" id="needChangeImage" isDown="true" src="D:\vue _workspace\chat_platform\src\imgs\chevron-down.svg" alt="">
            </div>
            <div class="collapse" id="auth" style="">
              <ul class="nav flex-column sub-menu px-3">
                <li class="nav-item " v-for="(item,index) in collegeList" :key="index">
                   <button :key="index" @click="goProjextList(item)"
                    class="nav-link text-dark" >{{ item }}</button></li>
              </ul>
            </div>
          </li>
</ul>
 <div class="col-10">
  <Suspense>
    <RouterView></RouterView>
  </Suspense>

</div>
</div>
 </div>
</template>

<script setup>
import { onUpdated, reactive,ref,watch, watchEffect } from 'vue';
import {useRoute,useRouter} from 'vue-router'
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment';
import { useChatwebsocketStore } from '@/store/chatwebsocket';

//获取1000聊天室的最后一条公告
const getLastNotice=async ()=>{
  let result=await axios({
    method:"get",
    url:"http://localhost:8080/getChatroomNotice",
    params:{
      chatroom_id:"1000"
    }
  })
  let length=result.data.length
  return result.data[length-1]
}

//查看最后一条公告是否已经读过
const checkLastNotice=async ()=>{
  let noticeLast=await getLastNotice()
  //根据用户ID和公告ID查是否已经读过
  let result=await axios({
    method:"get",
    url:"http://localhost:8080/getIsRead",
    params:{
      user_id:user_id,
      notice_id:noticeLast.notice_id
    }
  })
  return result.data
}

const open = async() => {
  let noticeLast=await getLastNotice()
  ElMessageBox.alert(noticeLast.notice_content, noticeLast.publish_time+'系统公告', {
    showConfirmButton:checkLastNotice()==false?true:false,
    confirmButtonText: '确认已读',
    callback: async(action) => {
      ElMessage({
        type: 'success',
        message:"确认成功",
      })
      //修改后台数据
      let result=await axios({
        method:"get",
        url:"http://localhost:8080/haveRead",
        params:{
          user_id:user_id
        }
      })
    },
  })
}

const drawer = ref(false)
const route=useRoute()
const router=useRouter()
let dialogMessage=ref({})
let student=reactive({
  student_id:"",
  student_name:"",
  student_sex:"",
  college:"",
  major:"",
  interest:"",
  search_exper:""
})
let teacher=reactive({
    teacher_id:"",
    teacher_name:"",
    teacher_sex:"",
    college:"",
    department:"",
    courses:"",
    research_exper:"",
    phone:"",
 })

//获取从路由中获取user_id
let user_id=route.query.user_id
//从路由中获取类型
let type=route.query.type
if(type){
  sessionStorage.setItem("type",type)
}else{
  type=sessionStorage.getItem("type")
}

 //异步请求获取老师信息
 const getTeacherData=async()=>{
     //根据获取到的student_id来查询学生的信息
   teacher.teacher_id=user_id
     if(teacher.teacher_id){
       let result=await axios({
         method:'get',
         url:"http://localhost:8080/getTeacherByID",
         params:{
           teacher_id:teacher.teacher_id
         }
       })
       return result.data.teacher_name
 }
 }

//异步请求获取学生信息
const getStudentData=async()=>{
    //根据获取到的student_id来查询学生的信息
  student.student_id=user_id
    if(student.student_id){
      let result=await axios({
        method:'get',
        url:"http://localhost:8080/getStuById",
        params:{
          student_id:student.student_id
        }
      })
      return result.data.student_name
}
}

let user_name=ref("")
if(type=="teacher"){
  user_name.value=await getTeacherData()
  sessionStorage.setItem("user_name",user_name.value)
}
if(type=="student"){
  user_name.value=await getStudentData()
  sessionStorage.setItem("user_name",user_name.value)
}

let message=reactive({
  message_id:"",
  sender_id:user_id,
  send_time:"",
  receiver_id:"",
  content:"",
  system:false,
  watch:false,
  sender_name:user_name.value,
  receiver_name:"",
  online:false
})
let isDown=true

//点击改变图片的形状
function changImg()
{
  
  let element = document.getElementById("needChangeImage");//获取需要改变的照片的DOM元素
  let elemnetShow=document.getElementById("auth") //获取需要显示的元素

  if(isDown){
    element.setAttribute("src", "/src/imgs/chevron-up.svg");
    isDown=false
    //显示
    elemnetShow.setAttribute("class","collapse show")
  }
  else{
    element.setAttribute("src", "/src/imgs/chevron-down.svg");
    isDown=true
    elemnetShow.setAttribute("class","collapse")
  }
}
// setTimeout(() => {
//     router.push({path:'/stuIndex/index',query:{student_id:student.student_id}})
// }, 400);
//跳转到学生的个人信息界面
function goToInfo(){
  if(type=="student"){
    router.push({path:'/index/stuinfo',query:{student_id:user_id,user_id:user_id}})
  }
  if(type=="teacher"){
    router.push({path:'/index/teainfo',query:{teacher_id:user_id,user_id:user_id}})
  }
}

//点开界面之后，自动建立websocket连接
const getconnection=async()=>{
  let ws=new WebSocket("ws://localhost:8080/message/"+user_id);
  return ws
}
let ws=await getconnection()

let inputMessage=ref("")
let messageLength=ref(0)
let senderList=ref([])
let messageList=reactive({})  //存放 发送者->[message,message]
let messageNumber=ref({})  //存放 发送者->未读的消息条数
let receiverID=ref({})

ws.onopen=function(){
  console.log("连接已经建立")
}
ws.onmessage=async function(evt){
  let tempMessage=JSON.parse(evt.data)//消息JSON化
  console.log(tempMessage)
  if(!tempMessage.system){
    let sender=tempMessage.sender_name   //先获取消息的发送者
    let receiver=tempMessage.receiver_name //获取消息的接受者
    if(user_name.value==""){
      user_name.value=sessionStorage.getItem("user_name")
    }
    //先判断字典中是否有这个发送方
    if(sender!=user_name.value && !messageList.hasOwnProperty(sender)){
      messageList[sender]=[]
      dialogMessage.value[sender]=false
      messageNumber.value[sender]=0
      receiverID.value[sender]=tempMessage.sender_id
    }
    if(sender==user_name.value && !messageList.hasOwnProperty(receiver) ){//如果发送消息是自己
      messageList[receiver]=[]
      dialogMessage.value[receiver]=false
      messageNumber.value[receiver]=0
      receiverID.value[receiver]=tempMessage.receiver_id
    }
    //将没有读过的消息数量显示出来
    if(sender!=user_name.value && !tempMessage.watch && !tempMessage.online){
      messageNumber.value[sender]+=1
    }
    //放置消息
    if(sender==user_name.value){
      messageList[receiver].push(tempMessage)
    }else{
      messageList[sender].push(tempMessage)
    }
    //如果用户在线并且和发送者的聊天框处于打开的状态消息认为是已读的
    if(tempMessage.online && dialogMessage.value[sender]){
      //给数据库发送消息，此条消息已读
      await axios({
        method:"get",
        url:"http://localhost:8080/updateMessageWatch",
        params:{
          message_id:tempMessage.message_id
        }
      })
    }
    //如果用户在线，但是聊天框没有打开，则认为消息是未读的
    if(tempMessage.online && !dialogMessage.value[sender]){
      messageNumber.value[sender]+=1
    }
  }else{
    //如果是系统消息的话先判断这个聊天室是否存在，如果存在的话，弹窗
    let chatroom_id=tempMessage.content
    //根据聊天室的ID判断聊天室是否存在，如果存在的话弹窗邀请
    let result=await axios({
      method:"get",
      url:"http://localhost:8080/getChatroomByID",
      params:{
        chatroom_id:chatroom_id
      }
    })
    if(result.data && result.data.admin_id!=user_id){
      console.log("-----")
      let chatroom=result.data
      ElMessageBox.alert(chatroom.admin_name+"邀请你加入关于:"+chatroom.project_name+"的交流", '聊天室邀请', {
    confirmButtonText: '加入',
    callback: () => {
      //跳转到指定的路由
      router.push({path:'/index/liveChatroom',query:{
            chatroom_id:chatroom.chatroom_id,
            user_id:user_id,
            project_name:chatroom.project_name
            }})
    },
  })
    }
  }
}

//另一个组件传来消息之后，也相当于发送过来消息：先检测有数据，再更新消息列表
const chatWebsocket=useChatwebsocketStore()
watch(()=>chatWebsocket.isClear,()=>{
  messageList=reactive({})  //重新赋值导致了messageList检测不到了
  //重新开启监听
  //当消息列表发生变化时就去更新一下，发送者列表
  watch(messageList,(newValue)=>{
    senderList.value=Object.keys(newValue)
    //求所有未读过的消息总数
    messageLength.value=Object.values(messageNumber.value).reduce((a,b)=>a+b,0)
  },{deep:true})

})

watch(()=>chatWebsocket.isConnected,async ()=>{
  let tempMessage=chatWebsocket.message//从pinia中获取消息
  console.log(tempMessage)
  if(!tempMessage.system){
    let sender=tempMessage.sender_name   //先获取消息的发送者
    let receiver=tempMessage.receiver_name //获取消息的接受者
    if(user_name.value==""){
      user_name.value=sessionStorage.getItem("user_name")
    }
    //先判断字典中是否有这个发送方
    if(sender!=user_name.value && !messageList.hasOwnProperty(sender)){
      messageList[sender]=[]
      dialogMessage.value[sender]=false
      messageNumber.value[sender]=0
      receiverID.value[sender]=tempMessage.sender_id
    }
    if(sender==user_name.value && !messageList.hasOwnProperty(receiver) ){//如果发送消息是自己
      messageList[receiver]=[]
      dialogMessage.value[receiver]=false
      messageNumber.value[receiver]=0
      receiverID.value[receiver]=tempMessage.receiver_id
    }
    //将没有读过的消息数量显示出来
    if(sender!=user_name.value && !tempMessage.watch && !tempMessage.online){
      messageNumber.value[sender]+=1
    }
    //放置消息
    if(sender==user_name.value){
      messageList[receiver].push(tempMessage)
    }else{
      messageList[sender].push(tempMessage)
    }

    //如果用户在线并且和发送者的聊天框处于打开的状态消息认为是已读的
    if(tempMessage.online && dialogMessage.value[sender]){
      //给数据库发送消息，此条消息已读
      await axios({
        method:"get",
        url:"http://localhost:8080/updateMessageWatch",
        params:{
          message_id:tempMessage.message_id
        }
      })
    }

    //如果用户在线，但是聊天框没有打开，则认为消息是未读的
    if(tempMessage.online && !dialogMessage.value[sender]){
      messageNumber.value[sender]+=1
    }
  }else{
    //如果是系统消息的话先判断这个聊天室是否存在，如果存在的话，弹窗
    let chatroom_id=tempMessage.content
    //根据聊天室的ID判断聊天室是否存在，如果存在的话弹窗邀请
    let result=await axios({
      method:"get",
      url:"http://localhost:8080/getChatroomByID",
      params:{
        chatroom_id:chatroom_id
      }
    })
    if(result.data && result.data.admin_id!=user_id){
      console.log("-----")
      let chatroom=result.data
      ElMessageBox.alert(chatroom.admin_name+"邀请你加入关于:"+chatroom.project_name+"的交流", '聊天室邀请', {
    confirmButtonText: '加入',
    callback: () => {
      //跳转到指定的路由
      router.push({path:'/index/liveChatroom',query:{
            chatroom_id:chatroom.chatroom_id,
            user_id:user_id,
            project_name:chatroom.project_name
            }})
    },
  })
    }
  }
})

//当消息列表发生变化时就去更新一下，发送者列表
watch(messageList,(newValue)=>{
  senderList.value=Object.keys(newValue)
  //求所有未读过的消息总数
  messageLength.value=Object.values(messageNumber.value).reduce((a,b)=>a+b,0)
},{deep:true})

//打开聊天框
async function selectDialog(item,notReadNumber,index){//每次打开聊天框
  dialogMessage.value[item]=true
  messageNumber.value[item]=0 //对item的未读消息设置为0  数据库中：sender_name=item && recerive_name=student_name
  messageLength.value=Object.values(messageNumber.value).reduce((a,b)=>a+b,0)
  await axios({
    method:"get",
    url:"http://localhost:8080/updateMessageWatchByRS",
    params:{
      receiver_name:user_name.value,
      sender_name:item
    }
  })

  //获取聊天框DOM元素
  let elementID='chatWindow'+index
  if(notReadNumber){//如果未读消息数不为0的话
  let allMessageNumber=document.getElementById(elementID).getElementsByTagName("li").length
  let nextDom=document.getElementById(elementID).getElementsByTagName("li")[allMessageNumber-notReadNumber]
  nextDom.insertAdjacentHTML('beforebegin',"<div class='text-danger d-flex justify-center' id='notReadMessage'>--------未读消息--------</div>")
 }

  //界面打开之后，让滚动条自动滑到适合的位置
  autoToBottom(elementID)

  //检测每个聊天框中的信息，如果发现有消息变化的话，也进行滚轮的滚动
  watch(messageList[item],()=>{
    //第一步先删除未读消息提示
    let element= document.getElementById("notReadMessage")
    if(element){
      element.remove()
    }
    //第二步让滚轮下移
    autoToBottom(elementID)
  })
}

//聊天框关闭的时候
function closeChatWindow(item){
 let element= document.getElementById("notReadMessage")
 if(element){
  element.remove()
 }
  dialogMessage.value[item]=false
}

//关闭窗口时执行
function closeWindow(){
  console.log("111")
}

let isHaveSendMessage=ref(0)
async function sendMessage(receiver_id,item,index){
  message.send_time=moment().format('YYYY-MM-DD HH:mm:ss')
  message.receiver_id=receiver_id
  message.receiver_name=item
  message.content=inputMessage.value
  message.sender_name=user_name.value
  message.system=false
  ws.send(JSON.stringify(message)) //将信息发送
  await messageList[item].push(JSON.parse(JSON.stringify(message)))
  inputMessage.value=""
  isHaveSendMessage.value+=1

  //每次发送完消息后都自己将滚动条拉到最下面
  let elementID='chatWindow'+index
  autoToBottom(elementID)
}
function isSelf(sender_name){
  if(sender_name==user_name.value){
    return "row-col-1 mt-1 d-flex flex-row-reverse"
  }
  else{
    return "row-col-1 mt-1 d-flex"
  }
}

//为了在界面刷新的时候，已经连接的websocket连接不会被再次连接。
window.addEventListener('beforeunload',()=>{
  ws.close()
})
//查看消息
const watchMessage = (message,index) => {
  ElMessageBox.alert(message.content, '来自'+message.sender_name+"的消息：", {
    confirmButtonText: '查看',
    callback: () => {
      message.watch=true
      ws.send(JSON.stringify(message))
      ElMessage({
        type: 'info',
        message: '消息查看成功',
      })
      //重新渲染一下消息列表
      messageList.value.splice(index,1)
      messageLength.value=messageList.value.length
    },
  })
}


function getChange(){
  console.log("滑动了")
}

//控制聊天框滚动条,每次滑动到最底部
function autoToBottom(elementID){
  let chatWindow=document.getElementById(elementID)
  console.log(chatWindow)
  console.log(chatWindow.scrollHeight)
  chatWindow.scroll(0,chatWindow.scrollHeight)
}
let collegeList=ref("")
//获取所有的学院
const getAllCollege=async()=>{
  let result=await axios({
    method:"get",
    url:"http://localhost:8080/getAllCollege"
  })
  return result.data
}
collegeList.value=await getAllCollege()

function goReserve(){
  if(type=="student"){
    router.push({path:"/index/stuReserve",query:{user_id:user_id,student_id:user_id}})
  }
  if(type=="teacher"){
    router.push({path:"/index/teaReserve",query:{user_id:user_id,teacher_id:user_id}})
  }
}

function goProjextList(item){
  if(type=="student"){
    router.push({path:"/index/projectList",query:{college:item,student_id:user_id,user_id:user_id,student_name:user_name}})
  }
  if(type=="teacher"){
    router.push({path:"/index/projectListTeacher",query:{college:item,user_id:user_id}})
  }
}

ws.onclose=function(){
  console.log("连接已经断开")
}

</script>
<style scoped>
</style>